/**
 * 
 */
package ch.baeni.jee.service;

import javax.ejb.Stateless;
import javax.enterprise.event.Event;
import javax.inject.Inject;
import javax.persistence.EntityManager;

import ch.baeni.jee.data.UserRepository;
import ch.baeni.jee.model.User;
import ch.baeni.jee.util.SLL_Globals;
import ch.baeni.jee.util.SLL_Globals.LoginStatus;

/**
 * @author Benjamin
 *
 */
@Stateless
public class UserService {

    @Inject
    private EntityManager em;

    @Inject
    private Event<User> userEventSrc;
    
    @Inject
	private UserRepository userRep;
	
	/**
	 * @param user
	 */
	public void saveUser(User user) {
//		log.info("Name " + user.getName());
		em.persist(em.merge(user));
        userEventSrc.fire(user);
	}
	/**
	 * @param user
	 */
	public void updateUser(User user) {
		em.merge(user);
        userEventSrc.fire(user);
	}
	/**
	 * @param user
	 */
	public void deleteUser(User user) {
		em.remove(em.merge(user));
	}
	
	/**
	 * @param username
	 * @param password
	 * @return
	 */
	public User doLogin(String username, String password) {
		User user = userRep.findUserByUsername(username);

		if (user != null) {

			if (user.getPassword() != null && !user.getPassword().equals(SLL_Globals.getHashCode(password))){
				// passwort ist unkorrekt
				user.setLoginStatus(LoginStatus.INVALID_USERNAME_OR_PASSWORD);
			} else if (!user.isActive()){
				// user ist inaktiv
				user.setLoginStatus(LoginStatus.INACTIVE);
			} else {
				// erfolgreich login
				user.setLoginStatus(LoginStatus.SUCCESSFUL);
			}
		} else {
			// kein user mit dem Username
			user = null;
		}

		return user;
	}
}
